package org.nowcoder.leetcode.BTree;

/**
 * Title  : 105. Construct Binary Tree from Preorder and Inorder Traversal
 * Source : https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 * Author : XrazYang
 * Date   : 2023-09-12
 */

public class LeetCode_105 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int len = preorder.length;
        return buildTree2(inorder, 0, len - 1, preorder, 0, len - 1);
    }

    private TreeNode buildTree2(int[] inorder, int iLeft, int iRight, int[] preorder, int pLeft, int pRight) {
        //根据前序对中序进行切割
        int index = -1;
        for (int i = iLeft; i <= iRight; i++) {
            if (inorder[i] == preorder[pLeft]) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            int size = index - iLeft;
            TreeNode node = new TreeNode(inorder[index]);
            node.left = buildTree2(inorder, iLeft, index - 1, preorder, pLeft + 1, pLeft + size);
            node.right = buildTree2(inorder, index + 1, iRight, preorder, pLeft + size + 1, pRight);
            return node;
        }
        return null;
    }
}
